<template>
  <div class="all-circle">
    <!-- 筛选按钮 -->
    <div class="filter-container">
      <!-- 设置个人号 -->
      <el-select
        v-model.trim="username"
        size="small"
        placeholder="全部个人号"
        style="width: 200px"
        clearable
        @keyup.enter.native="handleFilter"
      >
        <el-option v-for="item in wechats" :key="item.wechatid" :label="item.wechatnick" :value="item.wechatid" />
      </el-select>

      <!-- 指定字段 -->
      <el-input
        v-model="searchContent"
        size="small"
        style="width: 200px; margin-left: 10px"
        clearable
        placeholder="评论内容"
        class="input-with-select"
      ></el-input>

      <!-- 设置时间段 -->
      <el-date-picker
        v-model="timePick"
        size="small"
        style="margin-left: 10px"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
      ></el-date-picker>
      <el-button size="small" style="margin-left: 10px" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>

      <!-- <el-button style="margin-left: 10px" icon="el-icon-edit" @click="resetData">重置</el-button> -->

      <!-- <el-button :loading="downloadLoading" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
    </div>

    <!-- 数据展示 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="commentsList"
      border
      fit
      highlight-current-row
      style="width: 99%"
      @selection-change="commentSelectionChange"
    >
      <el-table-column label="所属个人号" align="center">
        <template slot-scope="{ row }">
          <div v-if="wechatsMap[row.circle_wechatid]">
            <el-row type="flex" align="middle">
              <!-- <el-avatar :size="40" :src="wechatsMap[row.circle_wechatid].avatar">
                <i class="fa fa-picture-o" aria-hidden="true" title="头像miss"></i>
              </el-avatar> -->
              <div style="display: flex; flex-direction: column; margin-left: 10px">
                <span v-if="wechatsMap[row.circle_wechatid]" v-text="wechatsMap[row.circle_wechatid].wechatnick"></span>
                <span v-else v-text="row.circle_wechatid"></span>
              </div>
            </el-row>
          </div>

          <span v-else v-text="row.circle_wechatid"></span>
        </template>
      </el-table-column>

      <el-table-column prop="publishtime" label="评论时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ new Date(row.publishtime).toLocaleString() }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="fromname" label="评论人" align="center"></el-table-column>

      <el-table-column prop="toname" label="回复对象" align="center"></el-table-column>

      <el-table-column prop="remarks" label="朋友圈内容" align="center" min-width="120px">
        <template slot-scope="{ row }">
          <div class="circle-content" v-html="decodeCircleContent(row.remarks)"></div>
        </template>
      </el-table-column>

      <el-table-column prop="comment" label="评论内容" align="center"></el-table-column>

      <el-table-column prop="flag" label="跟评与否" align="center" min-width="80px">
        <template slot-scope="{ row }">
          <span v-if="row.flag" style="color: red">已跟评</span>
          <span v-else>未跟评</span>
        </template>
      </el-table-column>

      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column label="操作" align="center" min-width="180" class-name="my-comment-btn-cell">
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="showCommentPrefix($event, row)">跟评</el-button>
          <el-button type="primary" size="mini" @click="replyComment(row)">回复</el-button>
          <el-button type="primary" size="mini" @click="showDetail(row)">详情</el-button>
          <el-button size="mini" type="danger" @click="deleteComment(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pageNo"
      :limit.sync="pageSize"
      @pagination="getCommentsList"
    />

    <div v-if="showPrefix" class="show-model" @click="showPrefix = false"></div>
    <div v-show="showPrefix" id="followComment">
      <div class="follow-comment">
        <el-radio v-model="commentPrefix" label="同学：">同学：</el-radio>
        <el-radio v-model="commentPrefix" label="楼主：">楼主：</el-radio>
        <el-radio v-model="commentPrefix" label="网友：">网友：</el-radio>
        <el-radio v-model="commentPrefix" label="空">空</el-radio>
        <el-button type="primary" size="mini" @click="replyCommentByPrepend">确定</el-button>
      </div>
    </div>

    <el-dialog append-to-body title="朋友圈详情" class="circle-detail-dialog" :visible.sync="detailDialog" width="80%">
      <CircleDetail v-if="detailDialog" />
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapGetters } from 'vuex'

import Pagination from '@/components/Pagination' // 基于el-pagination组件封装的分页主键
import CircleDetail from './CircleDetail.vue'

import { getAllDevices } from '@/api/admin/device'
import { CircleCommentReplyTask } from '@/api/webSocketApi'
import { getCircleComments, deleteCircleComment, followCircleComments } from '@/api/front/circle'

export default {
  name: 'AllCircle',
  components: { Pagination, CircleDetail },
  data() {
    return {
      wechats: [], // 所有的微信
      wechatsMap: {}, // 微信id-info map
      username: '', // 微信id
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      timePick: '', // 时间段
      // select: '', // 评论内容
      searchContent: '', // 评论内容

      showPrefix: false, // 展示前缀
      commentPrefix: '空', // 评论前缀
      followCommentContent: {}, // 跟评的内容

      listLoading: true, // 正在获取数据
      commentsList: [], // 表格中的数据

      total: 0, // 数据总数
      pageNo: 1, // 页
      pageSize: 20, // 页面大小

      dialogType: '', // 添加还是编辑
      dialogVisible: false, // 展示dialog
      downloadLoading: false,
      showMoreInfo: false, // 展示更多信息
      tableKey: 0, // 表的key 改变可以重新渲染表
      dialogWxVisible: false, // 展示微信详情
      wxDetail: {}, // 微信详情
      detailDialog: false,
      commentsSelection: []
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser'
    })
  },
  created() {
    // 获取所有的账号信息
    this.getWechatsList()
    // 获取评论列表
    this.getCommentsList()
  },
  destroyed() {
    this.showPrefix = false
  },

  methods: {
    // 选择跟评
    commentSelectionChange(val) {
      this.commentsSelection = val
    },
    // 获取所有的账号信息
    getWechatsList() {
      getAllDevices(this.currentUser.SupplierId, this.currentUser.UnionId).then((res) => {
        this.wechats = res?.data || []
        const wm = {}
        this.wechats.forEach((x) => {
          wm[x.wechatid] = x
        })
        this.wechatsMap = wm
      })
    },
    // 获取评论列表
    async getCommentsList() {
      let startTime = ''
      let endTime = ''
      if (this.timePick) {
        startTime = dayjs(this.timePick[0]).format('YYYY-MM-DD')
        endTime = dayjs(this.timePick[1]).format('YYYY-MM-DD')
      }
      getCircleComments(
        this.currentUser.SupplierId,
        this.pageNo,
        this.pageSize,
        this.username,
        this.searchContent,
        startTime,
        endTime
      ).then((res) => {
        this.commentsList = res?.data?.rows || []
        this.total = res?.data?.records || 0
        this.listLoading = false
      })
    },
    // 搜索
    handleFilter() {
      this.pageNo = 1
      this.getCommentsList()
    },
    // 解析朋友圈内容
    decodeCircleContent(content) {
      try {
        const jContent = JSON.parse(content)
        const { circleType, textContent, attachtContent } = jContent
        let AttachContent = []
        if (attachtContent) {
          AttachContent = attachtContent.split(',')
        }
        if (circleType === 'text') {
          return `<p>${textContent}</p>`
        } else if (circleType === 'picture') {
          let imgStr = ''
          for (const ac of AttachContent) {
            imgStr = imgStr + `<img style="width:33%;padding:5px;object-fit:cover;" src="${ac}" />`
          }
          return `<p>${textContent}</p>
              <div style="display:flex;flex-wrap:wrap;">${imgStr}</div>
              `
        } else if (circleType === 'video') {
          return `<p>${textContent}</p>
            <video style="padding:5px;" src="${attachtContent}" controls></video>
            `
        } else {
          // 链接
          const title = AttachContent[1]
          const imgUrl = AttachContent[2]
          return `<p>${textContent}</p>
            <div style="display:flex;align-items:center;">
            <img style="width:30%;margin-right:5px;" src="${imgUrl}" />
            <span>${title}</span>
            </div>
            `
        }
      } catch (error) {
        return content
      }
    },
    // 导出数据到xml
    handleDownload() {
      this.downloadLoading = true
      // import('@/vendor/Export2Excel').then((excel) => {
      //   const tHeader = ['设备号', '激活码', '手机品牌', '手机型号', '创建时间']
      //   const filterVal = ['deviceId', 'activationCode', 'phoneBrand', 'phoneModel', 'createdAt']
      //   const data = this.formatJson(filterVal)
      //   excel.export_json_to_excel({
      //     header: tHeader,
      //     data,
      //     filename: 'devices'
      //   })
      //   this.downloadLoading = false
      // })
    },
    formatJson(filterVal) {
      return this.commentsList.map((v) =>
        filterVal.map((j) => {
          if (j === 'createdAt') {
            return new Date(v[j]).toLocaleString()
          } else {
            return v[j]
          }
        })
      )
    },
    // 评论详情
    showDetail(comment) {
      this.$store.commit('circleManager/SET_CIRCLE_DATA', { ...comment, ...{ id: comment.taskid }})
      this.detailDialog = true
    },
    // 回复
    replyComment(comment) {
      const { circle_wechatid, fromwechatid, circleid, commentid } = comment
      if (circle_wechatid === fromwechatid) {
        this.$message.warning('不能回复自己的评论！')
        return
      }

      this.$prompt('请输入评论内容', '评论', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S{1,500}/,
        inputErrorMessage: '评论字数1-500'
      })
        .then(({ value }) => {
          CircleCommentReplyTask(circle_wechatid, circleid, value, fromwechatid, commentid)
          this.$message.success('任务已经下发，请稍后刷新数据！')
        })
        .catch(() => {})
    },
    // 展示跟评
    showCommentPrefix(e, row) {
      this.followCommentContent = row
      const left = e.pageX - 440 + 30
      const top = e.pageY + 30
      const fcDom = document.getElementById('followComment')
      if (fcDom) {
        fcDom.style.top = top + 'px'
        fcDom.style.left = left + 'px'
      }
      this.showPrefix = true
    },
    // 跟评
    replyCommentByPrepend() {
      if (this.commentsSelection.length > 0) {
        for (const cs of this.commentsSelection) {
          const { circle_wechatid, circleid, comment, id } = cs
          let commentConntent = comment
          if (this.commentPrefix !== '空') {
            commentConntent = this.commentPrefix + comment
          }
          followCircleComments(circle_wechatid, circleid, commentConntent, id)
          // .then((res) => {
          //   // if (res.code === 0) {
          //   }
          // })
        }
        this.$message.success('跟评任务已经下发，请稍后刷新数据！')
        this.showPrefix = false
      } else {
        const { circle_wechatid, circleid, comment, id } = this.followCommentContent
        let commentConntent = comment
        if (this.commentPrefix !== '空') {
          commentConntent = this.commentPrefix + comment
        }
        followCircleComments(circle_wechatid, circleid, commentConntent, id).then((res) => {
          if (res.code === 0) {
            this.$message.success('跟评任务已经下发，请稍后刷新数据！')
          }
        })
        this.showPrefix = false
      }
    },
    // 删除评论
    deleteComment(comment) {
      const { circle_wechatid, fromwechatid, id } = comment
      if (circle_wechatid !== fromwechatid) {
        this.$message.warning('该微信不能删除别人的评论！')
        return
      }

      this.$confirm('确认删除该评论 ?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteCircleComment(id).then((res) => {
            if (res.code === 0) {
              this.$message.success('任务已经下发，请稍后刷新数据！')
            }
          })
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.all-circle {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  // position: relative;
  .filter-container {
    margin-bottom: 20px;
  }
  ::v-deep .circle-content {
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    p {
      padding: 5px;
      text-align: start;
    }
  }
  ::v-deep .my-comment-btn-cell {
    .el-button {
      margin: 5px;
    }
  }

  #followComment {
    position: absolute;
    // top: 0;
    // left: 0;
    z-index: 100;
  }
  .show-model {
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }

  .follow-comment {
    // position: absolute;
    width: 440px;
    padding: 10px;
    border: solid #e7e7e7 1px;
    border-radius: 10px;
    box-shadow: 2px 2px 2px #e7e7e7;
    position: relative;
    background: #fff;

    &::before {
      content: '';
      border: 12px solid transparent;
      border-bottom: 12px solid #e7e7e7;
      position: absolute;
      top: -24px;
      right: 20px;
    }

    &::after {
      content: '';
      border: 10px solid transparent;
      border-bottom: 10px solid #fff;
      position: absolute;
      top: -20px;
      right: 22px;
    }
  }
}
</style>
